package com.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.product.enmu.DeletedEnum;
import com.product.enmu.OperatorType;
import com.product.entity.AssemblyLine;
import com.product.entity.DefectLog;
import com.product.entity.InspectRecords;
import com.product.mapper.InspectorCordsMapper;
import com.product.service.IAssemblyLineService;
import com.product.service.IDefectLogService;
import com.product.service.IInspectorCordsService;
import com.product.service.IOperationLogService;
import com.product.to.AddInspectorCordTo;
import com.product.utils.DetectionService;
import com.product.utils.PageUtils;
import com.product.vo.InspectorCordVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class InspectreCordsServiceImpl extends ServiceImpl<InspectorCordsMapper, InspectRecords> implements IInspectorCordsService {
    @Autowired
    private IOperationLogService operatorService;
    @Autowired
    private IAssemblyLineService assemblyLineService;
    @Autowired
    private DetectionService detectionService;
    @Autowired
    private IDefectLogService defectLogService;

    @Override
    public PageUtils getAllInspectorCords(Integer size, Integer current, Integer lineId, Integer orderItemId, Integer timeOrderBy) {
        Page<InspectRecords> inspectRecordsPage = new Page<>(current, size);
        LambdaQueryWrapper<InspectRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(lineId != null, InspectRecords::getLineId, lineId);
        queryWrapper.eq(orderItemId != null, InspectRecords::getOrderItemId, orderItemId);
        queryWrapper.orderBy(timeOrderBy != null, timeOrderBy != null && timeOrderBy == 0, InspectRecords::getUpdateTime);

        Page<InspectRecords> page = this.baseMapper.selectPage(inspectRecordsPage, queryWrapper);

        List<InspectorCordVo> orderVoList = page.getRecords().stream().map(item -> {
            InspectorCordVo inspectorCordVo = new InspectorCordVo();
            BeanUtils.copyProperties(item, inspectorCordVo);
            return inspectorCordVo;
        }).toList();
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(orderVoList);
        return pageUtils;
    }

    /**
     * 流水线产品检测
     *
     * @param inspectorCords
     */
    @Override
    public void addInspectorCords(AddInspectorCordTo inspectorCords) {
        AssemblyLine lineServiceOne = assemblyLineService.getOne(new LambdaQueryWrapper<AssemblyLine>().eq(AssemblyLine::getLineId, inspectorCords.getLineId()));
        Long itemId = lineServiceOne.getOrderItemId();

        LambdaQueryWrapper<InspectRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectRecords::getLineId, inspectorCords.getLineId()).and(q -> {
            q.eq(InspectRecords::getOrderItemId, itemId);
        });
        InspectRecords inspect = this.getOne(queryWrapper);

        //将图片发送到模型校验
        String url = null;
        try {
            url = detectionService.detectionFile(inspectorCords.getDefectFile());
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean defectionRes = Objects.nonNull(url);

        //查询当前流水线生成的产品是否已经存在，不存在就新增
        if (inspect == null) {
            InspectRecords newRecords = new InspectRecords();
            newRecords.setLineId(lineServiceOne.getLineId());
            newRecords.setOrderItemId(itemId);
            newRecords.setInspectNum(1L);
            newRecords.setDefectNum(defectionRes ? 0L : 1L);
            newRecords.setUpdateTime(LocalDateTime.now());
            this.save(newRecords);

            operatorService.addOperation(OperatorType.Insert.getCode(), "新增InspectRecord表");
        } else {
            inspect.setInspectNum(inspect.getInspectNum() + 1);
            inspect.setDefectNum(inspect.getDefectNum() + (defectionRes ? 0L : 1L));
            this.updateById(inspect);

            operatorService.addOperation(OperatorType.Update.getCode(), "修改InspectRecord表");
        }

        //如果检测不通过，就向检测缺陷表中插入数据
        if (!defectionRes) {
            DefectLog defectLog = new DefectLog();
            defectLog.setLineId(inspectorCords.getLineId());
            defectLog.setOrderItemId(itemId);
            defectLog.setPig(url);
            defectLogService.save(defectLog);
        }

//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
    }

    @Override
    public void deleteInspectorCords(Integer inspectorCordsId) {
        LambdaUpdateWrapper<InspectRecords> updateWrapper = new LambdaUpdateWrapper<InspectRecords>()
                .eq(InspectRecords::getInspectorId, inspectorCordsId)
                .set(InspectRecords::getDeleted, DeletedEnum.DELETE.getValue());
        this.baseMapper.update(updateWrapper);

        operatorService.addOperation(OperatorType.Delete.getCode(), "删除InspectRecord表");
    }

    @Override
    public void deleteInspectorCordss(List<Integer> inspectorCordsIds) {
        for (Integer inspectorCordsId : inspectorCordsIds) {
            deleteInspectorCords(inspectorCordsId);
        }
    }
}
